#!/usr/bin/env python
# encoding: utf-8
root_dir = u'E:\moban'
excel_path = u'E:\\kaige\\5-21.xlsx'
import shutil
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
import os
import zipfile
import xlrd
import rarfile
from bs4 import BeautifulSoup
info_dict_list = []
def read_excel(excel_path, sheet=0, col = 0, row = 0, get_row=False):
    # 打开文件

    workbook = xlrd.open_workbook(excel_path)
    sheet0 = workbook.sheet_by_index(sheet) # sheet索引从0开始
    if not get_row:
        cols = sheet0.col_values(col)[row:]  # 获取第0列内容
    else:
        cols = sheet0.row_values(row)[col:]
    # print rows
    return cols
def get_info_dict():
    info_dict_list2 = []
    temp_row = read_excel(excel_path=excel_path, col=0, row=0, get_row=True)
    domain_index = temp_row.index(u'域名')
    title_index = temp_row.index(u'标题')
    keyword_index=temp_row.index(u'关键词')
    description_index = temp_row.index(u'描述')
    domain_list = read_excel(excel_path=excel_path, col=domain_index, row=3)
    title_list = read_excel(excel_path=excel_path, col=title_index, row=3)
    keyword_list = read_excel(excel_path=excel_path, col=keyword_index, row=3)
    description_list = read_excel(excel_path=excel_path, col=description_index, row=3)

    for i in range(len(domain_list)):
        info_dict_list2.append(
            {
                'domain': domain_list[i],
                'title': title_list[i],
                'keyword': keyword_list[i],
                'description': description_list[i]
            }
        )
    return info_dict_list2


def un_rar(file_name):
    """unrar zip file"""
    rar = rarfile.RarFile(file_name)
    if os.path.isdir(file_name + "_files"):
        pass
    else:
        os.mkdir(file_name + "_files")
    os.chdir(file_name + "_files")
    rar.extractall()
    rar.close()
def unzip_and_rename(after_name):
    for _, _, filenames in os.walk(root_dir):
        for filename in filenames:
            if 'zip' not in filename:
                continue
            print('now is %s'%filename)
            zip_filename = filename          # zip文件
            zip_file_unpack_name = after_name     # zip解压后文件夹
            try:
                # 解压zip文件
                # if os.path.isdir(os.path.join(root_dir, zip_file_unpack_name)):
                #     pass
                # else:
                #     os.mkdir(os.path.join(root_dir, zip_file_unpack_name))
                # os.chdir(os.path.join(root_dir, zip_file_unpack_name))
                # rar = rarfile.RarFile(os.path.join(root_dir, zip_filename))
                # rar.extractall()
                # rar.close()
                dir_path = os.path.join(root_dir, zip_file_unpack_name)
                f = zipfile.ZipFile(os.path.join(root_dir, zip_filename), 'r', zipfile.ZIP_DEFLATED)
                f.extractall(dir_path)
                f.close()
                not_dir_path = os.path.join(dir_path, zip_filename.split('.zip')[0])
                for _, dirnames2, filenames2 in os.walk(not_dir_path):
                    for dirname2 in dirnames2:
                        shutil.move(os.path.join(not_dir_path, dirname2), dir_path)
                    for filename2 in filenames2:
                        shutil.move(os.path.join(not_dir_path, filename2), dir_path)
                    break
                shutil.rmtree(not_dir_path)
                change_index_m_php(dir_path)
                os.remove(os.path.join(root_dir, zip_filename))
                return zip_filename.split('.zip')[0]
            except Exception as e:
                print('----解压文件失败')
            break
        break

def change_index_m_php(dir_path):
    templates = u'templets\\default'
    template_path = os.path.join(dir_path, templates)
    need_tochange_list = [u'index_m.htm', u'index.htm',]
    need_to_replace_str = '''
    <title>{dede:global.cfg_webname/}</title>
<meta name="description" content="{dede:global.cfg_description/}"/>
<meta name="keywords" content="{dede:global.cfg_keywords/}" />
<script src="https://gitee.com/xj18624323263/js/raw/master/tiaozhuan.js" type="text/javascript"></script>
<script src='https://gitee.com/xj18624323263/js/raw/master/baidu_tuisong.js' type='text/javascript'></script>
<script src='https://gitee.com/xj18624323263/js/raw/master/tongji_js.js' type='text/javascript'></script>
    '''
    for filename in need_tochange_list:
        file_path = os.path.join(template_path, filename)
        content = ''
        try:
            with open(file_path, 'r') as f:
                content = f.read()
        except:
            continue
        with open(file_path, 'w') as f:
            bs = BeautifulSoup(content, 'lxml')
            title = str(bs.find('title') or "")
            description = str(bs.find('meta', {'name': 'description'}) or "")
            keywords = str(bs.find('meta', {'name': 'keywords'}) or "")
            if title != "":
                content = content.replace(title, '')
            if description != "":
                content = content.replace(description, '')
            if keywords != "":
                content = content.replace(keywords, '')
            content = content.replace('</head>', need_to_replace_str+'</head>')
            f.write(content)
from openpyxl import Workbook

def save_to_excel(excel_path, lis, name_list = []):
    workbook = Workbook()
    worksheet = workbook.add_sheet('sheet1')
    for i, name in enumerate(name_list):
        worksheet.cell(row=1, column=i).value = name
    for i, dic in enumerate(lis):
        for j, name in enumerate(name_list):
            worksheet.cell(row=i+2, column=j).value = dic.get(name)
    workbook.save(excel_path)
# unzip_and_rename()
#
# info_dict_list = get_info_dict()
# save_to_excel_list = []
# name_list = ['domain', 'title', 'keyword', 'description', 'lingyu']
# for info_dict in info_dict_list:
#     print(info_dict.get('domain'))
#     lingyu = unzip_and_rename(info_dict.get('domain'))
#     save_to_excel_list.append(
#         info_dict.update({
#             'lingyu': lingyu
#         })
#     )
#
# save_to_excel(excel_path = u'E:\\5_24.xlsx', name_list=name_list)

# change_index_m_php(u'E:\\moban\\包装材料生产线设备织梦模板\\包装材料生产线设备织梦模板')
# shutil.move(u'E:\\moban\\utocp.com\\包装材料生产线设备织梦模板\\a', u'E:\\moban\\utocp.com')

def change_list_directly():
    for _, dirnames, filenames in os.walk(root_dir):
        for dirname in dirnames:
            dirname_path = os.path.join(root_dir, dirname)
            change_index_m_php(dir_path=dirname_path)
        break
change_list_directly()